package com.zhenyi.zhengfang.miniapp;

import java.sql.SQLException;
import java.util.Date;

import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.zhengfang.common.model.ZfComment;
import com.zhengfang.common.model.ZfUser;
import com.zhenyi.zhengfang.core.ZFMiniAppController;

public class CommentController extends ZFMiniAppController {
	@Override
	public void list() {
        String commentId = getPara("commentId");
		Kv kv = Kv.create();
		kv.set("commentId", commentId);
		SqlPara sqlPara = db.getSqlPara("ZfFindComment", kv);
		Record result = db.findFirst(sqlPara);
//		String openId = getPara("openId");
//		Kv kv = Kv.create();
//		kv.set("openId", openId);
//		SqlPara sqlPara = db.getSqlPara("ZfFindComment", kv);
//		Record result = db.findFirst(sqlPara);
		renderSuccess(result);
	}

	@Override
	public void submit() {
		// Long UserId = getParaToLong("userId");
		String nickName = getPara("nickName");
		Integer type = getParaToInt("type");
		String content = getPara("content");
		Integer isReplied = getParaToInt("isReplied", 0);
		String replyContent = getPara("replyContent");
		String mobile = getPara("mobile");
		String avatarUrl = getPara("avatarUrl");
		String openId = getPara("openId");
		Integer gender = getParaToInt("gender");
		String formId = getPara("formId");
		
		boolean flag = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				
				ZfComment info = new ZfComment();
				info.setType(type);
				info.setContent(content);
				info.setIsReplied(isReplied);
				info.setReplyContent(replyContent);
				info.setAddTime(new Date());
				info.setFormId(formId);
				// 判断openid是否存在
				Kv kv = Kv.create();
				kv.set("openId", openId);
				SqlPara sqlPara = db.getSqlPara("ZfUserOpenId", kv);
				Record result = db.findFirst(sqlPara);
				// System.out.println("Count" + result);
				if (result.getLong("count") == 0) {
					ZfUser user = new ZfUser();
					user.setNickName(nickName);
					user.setMobile(mobile);
					user.setAvatarUrl(avatarUrl);
					user.setGender(gender);
					user.setOpenId(openId);
					if (!user.save()) {
						renderMsg("新增失败");
						return false;
					}
					info.setUserId(user.getId());
					if (!info.save()) {
						renderMsg("新增失败");
						return false;
					}
				} else {
					ZfUser user = ZfUser.dao.searchFirst("openId", openId);
					info.setUserId(user.getId());
					boolean flag = info.save();
					if (!flag) {
						renderMsg("保存失败");
						return false;
					}
				}
				return true;
			}
		});
		renderFlag(flag);
	}

}
